package com.gitee.poi.plugin.core.handler.data;

import com.gitee.poi.plugin.annotations.data.DateFormat;
import com.gitee.poi.plugin.model.CellModel;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangxin
 * @time 2018/10/26 17:06
 */
public class DateFormatProcessor extends AbstractDataProcessor implements HandlerDataAnnotation {

    @Override
    public boolean support(Field field) {
        return field.getType().isAssignableFrom(Date.class) && field.getAnnotation(DateFormat.class) != null;
    }

    @Override
    protected HandlerData getHandlerData(Field field) throws Exception {
        String format = field.getAnnotation(DateFormat.class).value();
        return new DateFormatFunction(format);
    }

    public static class DateFormatFunction implements HandlerData {

        private String format;

        public DateFormatFunction(String format) {
            this.format = format;
        }

        @Override
        public CellModel process(CellModel cellModel) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            cellModel.setValue(dateFormat.format(cellModel.getValue()));
            return cellModel;
        }
    }
}
